package com.alianzamedica.connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.objectsearch.connection.ConnectionInterface;

import com.alianzamedica.tools.Enviroment;

/**
 * @author Carlos
 * 
 */
public class ConnectionImpl implements ConnectionInterface {

	private Connection connection;

	public void open() throws Exception {
		Enviroment env = Enviroment.getInstance();
		Properties props = env.getConnectionProperties();
		String url = props.getProperty("url");
		String user = props.getProperty("user");
		String password = props.getProperty("password");
		Class.forName("com.mysql.jdbc.Driver").newInstance();
		connection = DriverManager.getConnection(url, user, password);
	}

	public Connection getConnection() {
		return connection;
	}

	public void close() throws SQLException {
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * cierra los resultsets de manera correcta.
	 * 
	 * @param rs
	 *            a leer.
	 */
	public void closeGracefully(ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (Exception e) {
			}
		}
	}

	/**
	 * cierra las sentencias preparadas de manera correcta.
	 * 
	 * @param psmt
	 *            parametro a cerrar.
	 */
	public void closeGracefully(PreparedStatement psmt) {
		if (psmt != null) {
			try {
				psmt.close();
			} catch (Exception e) {
			}
		}
	}

	/**
	 * cierra las sentencias de manera correcta sin mandar mensajes.
	 * 
	 * @param stmt
	 *            parametro a cerrar.
	 */
	public void closeGracefully(Statement stmt) {
		if (stmt != null) {
			try {
				stmt.close();
			} catch (Exception e) {
			}
		}
	}

}
